package com.readword.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.readword.entity.Examination;
import com.readword.entity.TextOrImg;
/**
* @ClassName: TextParserUtil
* @Description: 文本解析工具，整个系统的核心功能
* @author 码农小鹿
* @date 2024年1月10日 下午1:44:43
*
 */
public class TextParserUtil {
	private final static Logger logger = LoggerFactory.getLogger(TextParserUtil.class);

	/**
	* <strong>根据word整个文件的内容进行整理</strong>
	* @Title: getContent
	* @Description: <p>TODO</p>
	* @param content <p>word文档内容</p>
	* @return <p>试题的实体列表</p>
	* List<Examination>
	* @author 码农小鹿
	* @date 2024年1月10日 下午1:45:04
	 */
	public static List<Examination> getContent(String content) {
		logger.info("开始提取文档内容");
		List<Examination> conList = new ArrayList<Examination>();
        String[] topics = content.split(Cons.KEYWORD.TOPIC);
        // 根据【题目】关键词，将整个word文本拆分成每一个题目字符串
        // 然后开始遍历题目，解析出各个参数
        for (String topicStr : topics) {
        	if(!"".equals(topicStr) && null != topicStr) {
        		if(topicStr.indexOf(Cons.KEYWORD.TOPICITEM) > 0) {
        			/**
        			 * 如果存在题目子项，那么使用另外一种计算方式
        			 */
        			Examination exam = new Examination();
        			String[] topic_items = topicStr.split(Cons.KEYWORD.TOPICITEM);
        			for (int i = 0; i < topic_items.length; i++) {
        				String topicItem = topic_items[i];
						if(i == 0) {
							Map<String, List<TextOrImg>> map = getTextImgs(topicItem);
							List<TextOrImg> textlist = map.get(Cons.TEXTORIMG.TEXTLIST);
							exam.setTopics(textlist);
							for (TextOrImg img : map.get(Cons.TEXTORIMG.IMGLIST)) {
								exam.addImg(img.getVal());
							}
						}else {
							Examination examIeam = getExamination(Cons.KEYWORD.TOPIC + topicItem);
							if(null != examIeam) {
								exam.addItem(examIeam);
							}
						}
					}
    				conList.add(exam);
        		}else {
        			/**
        			 * 没有子项
        			 */
        			Examination exam = getExamination(Cons.KEYWORD.TOPIC + topicStr);
        			if(null != exam) {
        				conList.add(exam);
        			}
        		}
        	}
		}
		logger.info("提取文档内容完成");
		return conList;
	}

	/**
	* @Title: getExamination
	* @Description: <p>根据word拆分之后得到每一道题的字符串，然后使用正则提取每个关键词对应的内容</p>
	* @param text <p>根据word文档拆分之后的每一道题字符串进行转换成可视化数据</p>
	* @return <p>返回每一个试题的数据封装</p>
	* Examination
	* @author 码农小鹿
	* @date 2024年1月10日 下午1:46:00
	 */
	public static Examination getExamination(String text) {
		//logger.info("题目字符串：{}", text);
		Examination exam = new Examination();
        Pattern pattern = Pattern.compile(Cons.TOPIC);  
        Matcher matcher = pattern.matcher(text);  
        while (matcher.find()) {
        	String topicStr = matcher.group(1);
			Map<String, List<TextOrImg>> map = getTextImgs(topicStr);
			List<TextOrImg> textlist = map.get(Cons.TEXTORIMG.TEXTLIST);
			exam.setTopics(textlist);
			for (TextOrImg img : map.get(Cons.TEXTORIMG.IMGLIST)) {
				exam.addImg(img.getVal());
			}
            String item = matcher.group(2);
            String[] parts = item.split(Cons.ITEM_REGEX);  
            for (String part : parts) {
                if (!part.isEmpty()) {
                	for (String poin : Cons.TOOLS.getPoin()) {
                		// 将选项ABCD后面的一个.或者、去掉，即使没有也没关系，以备后患而已
                		part = part.replace(poin, "");
					}
                    exam.addOption(Cons.TOOLS.removeTrim(part));
                }  
            }
            exam.setAnswer(Cons.TOOLS.removeTrim(matcher.group(3)));
            exam.setAnalysis(Cons.TOOLS.removeTrim(matcher.group(4)));
            exam.setExamSite(Cons.TOOLS.removeTrim(matcher.group(5)));
            exam.setSource(Cons.TOOLS.removeTrim(matcher.group(6)));
            exam.setErrorProne(Cons.TOOLS.removeTrim(matcher.group(7)));
        }
        return exam;
	}
	
	public static Map<String, List<TextOrImg>> getTextImgs(String topicStr){
		Map<String, List<TextOrImg>> map = new HashMap<String, List<TextOrImg>>();
		List<TextOrImg> list = new ArrayList<TextOrImg>();
        List<TextOrImg> textlist = new ArrayList<TextOrImg>();
        List<TextOrImg> imglist = new ArrayList<TextOrImg>();
		String DICTREGEX = "\\$\\{([a-zA-Z0-9]*?)\\}";
		Pattern pattern = Pattern.compile(DICTREGEX);
        Matcher matcher = pattern.matcher(topicStr);
		List<String> matchs = new ArrayList<String>();
		List<String> matchImgs = new ArrayList<String>();
        while (matcher.find()) {
        	matchs.add(matcher.group(0));
        	matchImgs.add(Cons.FILE.SHOWFILE + matcher.group(1) + Cons.FILE.IMGSUFFIX);
        }
        for (String matchStr : matchs) {
        	topicStr = topicStr.replace(matchStr, Cons.SPLIT_IMG);
		}
        String[] splits = topicStr.split(Cons.SPLIT_IMG);
        int imgCount = 0;
        for (int i = 0; i < splits.length; i++) {
        	String split = splits[i];
        	if(!"".equals(split) && null != split) {
        		list.add(new TextOrImg().addText(split));
        	}
        	if(matchs.size() > 0 && i <=  matchs.size() - 1) {
        		list.add(new TextOrImg().addImg(matchImgs.get(i)));
        		imgCount ++;
        	}
		}
        if(imgCount < matchImgs.size()) {
        	// 如果图片加载的数量比解析出来的小，那么说明还有未加载的，因为放在最后面
        	for (int m = 0; m < matchImgs.size(); m++) {
        		if(m > imgCount-1) {
        			list.add(new TextOrImg().addImg(matchImgs.get(m)));
        		}
        	}
        }
        int lastIndex = -1;
        for (int i = list.size() - 1; i >= 0; i--) {
        	TextOrImg info = list.get(i);
        	if(info.getType() == 0) {
        		// 如果最后一个是文本，那么跳出
        		lastIndex =i;
        		break;
        	}
        }
		if(lastIndex >= 0) {
			textlist = list.subList(0, lastIndex+1);
			imglist = list.subList(lastIndex+1, list.size());
			map.put(Cons.TEXTORIMG.TEXTLIST, textlist);
			map.put(Cons.TEXTORIMG.IMGLIST, imglist);
		    return map;
		}
        map.put(Cons.TEXTORIMG.TEXTLIST, list);
    	map.put(Cons.TEXTORIMG.IMGLIST, imglist);
        return map;
	}
}
